package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.ConditionVO;
import com.itheima.sfbx.insurance.enums.ConditionEnum;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.ConditionMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.Condition;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.IConditionService;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：筛选项服务实现类
 */
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, Condition> implements IConditionService {

    @Autowired
    private ICategoryConditionService categoryConditionService;

    @Autowired
    private IInsuranceConditionService insuranceConditionService;

    @Override
    public Page<ConditionVO> findPage(ConditionVO conditionVO, int pageNum, int pageSize) {
        Page<Condition> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(conditionVO));

        return BeanConv.toPage(page, ConditionVO.class);
    }

    @Override
    public ConditionVO findById(String conditionId) {
        //TODO
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ConditionVO save(ConditionVO conditionVO) {
        Integer count = lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .eq(Condition::getDataState, SuperConstant.DATA_STATE_0)
                .count();

        if(count > 0){
            log.error("该key已存在");
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }

        Condition condition = BeanConv.toBean(conditionVO, Condition.class);

        this.save(condition);

        return BeanConv.toBean(condition, ConditionVO.class);
    }

    @Override
    @Transactional
    public Boolean update(ConditionVO conditionVO) {
        // 判断id是否存在
        Condition bean = getById(conditionVO.getId());
        if(bean==null){
            log.error("该保障项不存在");
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        // 判断该key除自己以外是否存在
        Integer count = lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .ne(Condition::getId, conditionVO.getId())
                .count();

        if(count>0){
            log.error("该key已存在");
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        // 判断 分类保障项&方案保障项 关系表是否存在关联项
        int count1 = judgeMiddleTableDataExist(conditionVO.getConditionKey());

        if(count1 > 0){
            log.error("该保障项已被关联，无法修改");
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        return updateById(BeanConv.toBean(conditionVO, Condition.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String[] checkedIds) {
        // 判断是否存在
        Condition bean = getById(checkedIds[0]);
        if(bean==null){
            log.error("删除失败，该数据不存在");
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }

        // 判断 分类保障项&方案保障项 关系表是否存在关联项
        int count1 = judgeMiddleTableDataExist(bean.getConditionKey());

        if(count1 > 0){
            log.error("该保障项已被关联，无法删除");
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }

        int result = baseMapper.deleteById(bean.getId());

        return result > 0;
    }

    @Override
    public List<ConditionVO> findList(ConditionVO conditionVO) {
        List<Condition> list = this.list(queryWrapper(conditionVO));

        return list.stream().map(s->BeanConv.toBean(s, ConditionVO.class)).collect(Collectors.toList());
    }

    @Override
    public List<ConditionVO> findInConditionKeys(List<String> conditionKeys) {

        List<Condition> conditionList = lambdaQuery()
                .in(Condition::getConditionKey, conditionKeys)
                .list();

        return BeanConv.toBeanList(conditionList, ConditionVO.class);
    }

    /**
     * 分页 list 共用的wrapper
     * @param conditionVO
     * @return
     */
    private LambdaQueryWrapper<Condition> queryWrapper(ConditionVO conditionVO){
        LambdaQueryWrapper<Condition> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(conditionVO.getConditionKey()), Condition::getConditionKey, conditionVO.getConditionKey())
                .like(StrUtil.isNotBlank(conditionVO.getConditionKeyName()), Condition::getConditionKeyName, conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotBlank(conditionVO.getDataState()), Condition::getDataState, conditionVO.getDataState());
        return lqw;
    }

    /**
     * 判断 分类保障项 & 方案保障项 关系表是否存在关联项
     * @param conditionKey
     * @return
     */
    private int judgeMiddleTableDataExist(String conditionKey){
        // 判断分类保障项是否存在关联项
        Integer count1 = categoryConditionService.lambdaQuery()
                .eq(CategoryCondition::getConditionKey, conditionKey)
                .count();

        // 判断方案保障项关系表是否存在关联项
        Integer count2 = insuranceConditionService.lambdaQuery()
                .eq(InsuranceCondition::getConditionKey, conditionKey)
                .count();

        if(count1>0 || count2>0){
            return 1;
        }
        return 0;
    }
}
